package ar.com.angel.exception.manager
{
	import ar.com.angel.alert.CustomAlert;
	import ar.com.angel.exception.ApplicationError;
	
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.mxml.RemoteObject;

	public class ApplicationErrorManager
	{
		private var lastListener:Function;
		private var lastFaultListener:Function;
		
		public function ApplicationErrorManager(destination:String=null)
		{
			this.addEventListener(ResultEvent.RESULT, callback);
			this.addEventListener(FaultEvent.FAULT,faultEventCallback);
			this.lastFaultListener = faultEventCallback;
		}
		
		public function set listener(callback:Function):void{
			lastListener = callback;	
		}
		
		public function set faultListener(_callback:Function):void{
			if (this.lastFaultListener != null) {
				this.removeEventListener(FaultEvent.FAULT, this.lastFaultListener);
			}
			this.addEventListener(FaultEvent.FAULT, _callback);
		}
		
		
		private function callback(event:ResultEvent):void{
			if(lastListener != null){
				if(event.result == null)
					lastListener.call(this);
				else
					lastListener.call(this,event.result);
			}
		}
		
		public function faultEventCallback(event:FaultEvent):void{
			ScreenBlocker.unblockScreen();//Esto por las dudas que este blockeante
			if (event.fault.rootCause is ApplicationError) {
				var error:ApplicationError = event.fault.rootCause as ApplicationError;
				CustomAlert.error(error.popupMessage);
				return;
			}
			CustomAlert.error("Ha ocurrido un error desconocido");
			trace("Error desconocido: " + event.fault.faultString);
		}
	}
}